package com.wangzhen.javastudy.other.other2;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liyongkang16
 * @date 2021-04-13
 * @description
 */

public class pmp2 {

    private static boolean success = false;
    private static boolean loginSuccess = false;
    private static String user = "";

    public static void main(String[] args) {
        for(int i=0;i<10;i++){
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    pmp2 pm = new pmp2();
                    pm.baoming();
                }
            });
            thread.start();
        }
    }

    private void baoming(){
        boolean allIsOk = false;//任意考点都行
        boolean needLogin = true;//是否先登录

        String time = "1618364881,1618372081,1618379281,1618379401";
        String time2 = "1618379401";

        String url = "http://exam.chinapmp.cn/App_Ajax/SHOW.Ajax.Exam.Login,SHOW.Ajax.ajax?from=http%3a%2f%2fuser.chinapmp.cn%2findex.shtml&domain=exam";
        //需填
        String data = "{\"JSON_DATA\":[{\"Name\":\"uType\",\"Value\":0},{\"Name\":\"uName\",\"Value\":\"你的用户名\"},{\"Name\":\"uPass\",\"Value\":\"你的密码\"}]}";


        if(!needLogin){
            System.out.println("");
            System.out.println("-------------------------已设置为不登录----------------------------");
            System.out.println("");
        }else{
            System.out.println("");
            System.out.println("-------------------------开始登录----------------------------");
            System.out.println("");
            try {
                int times = 0;
                while (true){
                    times++;
                    if(pmp2.success){
                        return;
                    }
                    if(pmp2.loginSuccess){
                        break;
                    }
                    CloseableHttpClient httpClient = HttpClients.createDefault();
                    try {
                        HttpPost httpPost = new HttpPost(url);
                        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
                        httpPost.setConfig(requestConfig);
                        httpPost.setHeader("Content-Type", "text/plain; charset=UTF-8");
                        httpPost.setHeader("Cookie", "SYSTEM_ONLY_COOKIE_NAME=E4D46EC44AF3B17B9EF2063D047F317D; SYSTEM_TEMP_COOKIE_NAME=4E435AFE3130C859186F052A9DD19134; user=cNWI10p6uab42kt_0n0qIv9i_yb_Yv8W; Hm_lvt_ce48bdfcf41472b5d96a1d490af19487="+time+"; Hm_lpvt_ce48bdfcf41472b5d96a1d490af19487="+time2);
                        httpPost.setHeader("Cache-Control", "no-cache");
                        httpPost.setHeader("Connection", "keep-alive");
                        httpPost.setHeader("X-UNEXT.Ajax-Method", "Save");
                        httpPost.setHeader("X-UNEXT.Ajax-Token", "cf9c94d1.1337E74021394F067ECF73E520CCA448");
                        HttpEntity httpEntity = new StringEntity(data, "UTF-8");
                        httpPost.setEntity(httpEntity);
                        HttpResponse response = null;
                        try {
                            response = httpClient.execute(httpPost);
                        } catch (IOException e) {
                            System.out.println("["+times+"] >> 请求超时，"+e.getMessage());
                            httpClient.close();
                            continue;
                        }
                        int statusCode = response.getStatusLine().getStatusCode();
                        System.out.println("["+times+"] >> "+Calendar.getInstance().getTime().toString()+" >> "+statusCode);
                        if(statusCode==200){
                            Header[] headers = response.getHeaders("Set-Cookie");
                            if(headers.length==0){
                                System.out.println("登录成功，但未返回用户信息");
                                break;
                            }
                            Header userHeader = headers[0];
                            String userHeaderStr = userHeader.getValue();
                            user = userHeaderStr.split(";")[0].split("=")[1];
                            System.out.println("user>>"+user);
                            HttpEntity entity = response.getEntity();
                            if (entity != null) {
                                InputStream is = entity.getContent();
                                BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                                String line = br.readLine();
                                StringBuilder sb = new StringBuilder();
                                while (line != null) {
                                    sb.append(line + "\n");
                                    line = br.readLine();
                                }
                                System.out.println(sb.toString());
                            }
                            pmp2.loginSuccess = true;
                            break;
                        }
                    }finally {
                        httpClient.close();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        System.out.println("");
        System.out.println("-------------------------开始查询报名信息----------------------------");
        System.out.println("");
        //查报名信息
        String editUrl= "http://user.chinapmp.cn/examsignedit.shtml?id=10890024";
        String baomingHtml = "";
        try {
            int times = 0;
            while (true){
                times++;
                if(pmp2.success){
                    return;
                }
                CloseableHttpClient httpClient = HttpClients.createDefault();
                try {
                    HttpGet httpGet = new HttpGet(editUrl);
                    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
                    httpGet.setConfig(requestConfig);
                    httpGet.setHeader("Cookie", "SYSTEM_ONLY_COOKIE_NAME=E4D46EC44AF3B17B9EF2063D047F317D; SYSTEM_TEMP_COOKIE_NAME=4E435AFE3130C859186F052A9DD19134; user="+user+"; Hm_lvt_ce48bdfcf41472b5d96a1d490af19487="+time+"; Hm_lpvt_ce48bdfcf41472b5d96a1d490af19487="+time2);
                    httpGet.setHeader("Cache-Control", "no-cache");
                    httpGet.setHeader("Connection", "keep-alive");
                    HttpResponse response = null;
                    try {
                        response = httpClient.execute(httpGet);
                    } catch (IOException e) {
                        System.out.println("["+times+"] >> 请求超时");
                        httpClient.close();
                        continue;
                    }
                    int statusCode = response.getStatusLine().getStatusCode();
                    System.out.println("["+times+"] >> "+Calendar.getInstance().getTime().toString()+" >> "+statusCode);
                    if(statusCode==200){
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            InputStream is = entity.getContent();
                            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                            String line = br.readLine();
                            StringBuilder sb = new StringBuilder();
                            while (line != null) {
                                sb.append(line + "\n");
                                line = br.readLine();
                            }
                            baomingHtml = sb.toString();
                        }
                        if(baomingHtml.contains("Kaodian")){
                            break;
                        }
                    }
                }finally {
                    httpClient.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("");
        System.out.println(baomingHtml);


        System.out.println("");
        System.out.println("-------------------------查询天津、廊坊、保定、石家庄考点----------------------------");
        System.out.println("");

        Document document = Jsoup.parse(baomingHtml);
        Element kaodianElement = document.getElementById("Kaodian");
        Elements elements = kaodianElement.select("option");
        //key为code，val为中文名
        Map<String, String> tianjinGH = new HashMap<>();
        Map<String, String> tianjinOther = new HashMap<>();
        Map<String, String> langfang = new HashMap<>();
        Map<String, String> baoding = new HashMap<>();
        Map<String, String> shijiazhuang = new HashMap<>();
        Map<String, String> zibo = new HashMap<>();
        Map<String, String> taiyuan = new HashMap<>();
        Map<String, String> weifang = new HashMap<>();
        Map<String, String> shenyang = new HashMap<>();

        //需填 优先级
        for (Element element : elements) {
            String name = element.html();
            String code = element.val();
            if(allIsOk){
                tianjinGH.put(code, name);
                continue;
            }
            if(name==null || "".equals(name)){
                continue;
            }
            //考点
            if(name.contains("天津")){//天津
                if(name.contains("光环")){
                    tianjinGH.put(code, name);
                }else{
                    tianjinOther.put(code, name);
                }
            }else  if(name.contains("保定")){//保定
                baoding.put(code, name);
            }else if(name.contains("石家庄")){//石家庄
                shijiazhuang.put(code, name);
            }else if(name.contains("淄博")){//淄博
                zibo.put(code, name);
            }else if(name.contains("太原")){//太原
                taiyuan.put(code, name);
            }else if(name.contains("潍坊")){//潍坊
                weifang.put(code, name);
            }else if(name.contains("沈阳")){//沈阳
                shenyang.put(code, name);
            }
        }

        List<Kaodian> kaodianList = new ArrayList<>();

        if(!tianjinGH.isEmpty()){
            System.out.println("天津光环考点个数："+tianjinGH.size());
            for (Map.Entry<String, String> stringStringEntry : tianjinGH.entrySet()) {
                Kaodian kaodian = new Kaodian();
                kaodian.setCode(stringStringEntry.getKey());
                kaodian.setName(stringStringEntry.getValue());
                kaodianList.add(kaodian);
            }
        }
        if(!tianjinOther.isEmpty()){
            System.out.println("天津考点个数："+tianjinGH.size());
            for (Map.Entry<String, String> stringStringEntry : tianjinOther.entrySet()) {
                Kaodian kaodian = new Kaodian();
                kaodian.setCode(stringStringEntry.getKey());
                kaodian.setName(stringStringEntry.getValue());
                kaodianList.add(kaodian);
            }
        }
        
        if(!baoding.isEmpty()){
            System.out.println("保定考点个数："+tianjinGH.size());
            for (Map.Entry<String, String> stringStringEntry : baoding.entrySet()) {
                Kaodian kaodian = new Kaodian();
                kaodian.setCode(stringStringEntry.getKey());
                kaodian.setName(stringStringEntry.getValue());
                kaodianList.add(kaodian);
            }
        }
        if(!shijiazhuang.isEmpty()){
            System.out.println("石家庄考点个数："+tianjinGH.size());
            for (Map.Entry<String, String> stringStringEntry : shijiazhuang.entrySet()) {
                Kaodian kaodian = new Kaodian();
                kaodian.setCode(stringStringEntry.getKey());
                kaodian.setName(stringStringEntry.getValue());
                kaodianList.add(kaodian);
            }
        }
        if(!zibo.isEmpty()){
            System.out.println("淄博考点个数："+tianjinGH.size());
            for (Map.Entry<String, String> stringStringEntry : zibo.entrySet()) {
                Kaodian kaodian = new Kaodian();
                kaodian.setCode(stringStringEntry.getKey());
                kaodian.setName(stringStringEntry.getValue());
                kaodianList.add(kaodian);
            }
        }
        if(!taiyuan.isEmpty()){
            System.out.println("太原考点个数："+tianjinGH.size());
            for (Map.Entry<String, String> stringStringEntry : taiyuan.entrySet()) {
                Kaodian kaodian = new Kaodian();
                kaodian.setCode(stringStringEntry.getKey());
                kaodian.setName(stringStringEntry.getValue());
                kaodianList.add(kaodian);
            }
        }
        if(!weifang.isEmpty()){
            System.out.println("潍坊考点个数："+tianjinGH.size());
            for (Map.Entry<String, String> stringStringEntry : weifang.entrySet()) {
                Kaodian kaodian = new Kaodian();
                kaodian.setCode(stringStringEntry.getKey());
                kaodian.setName(stringStringEntry.getValue());
                kaodianList.add(kaodian);
            }
        }
        if(!shenyang.isEmpty()){
            System.out.println("沈阳考点个数："+tianjinGH.size());
            for (Map.Entry<String, String> stringStringEntry : shenyang.entrySet()) {
                Kaodian kaodian = new Kaodian();
                kaodian.setCode(stringStringEntry.getKey());
                kaodian.setName(stringStringEntry.getValue());
                kaodianList.add(kaodian);
            }
        }
        //测试数据
//        Kaodian kaodianTest = new Kaodian();
//        kaodianTest.setCode("230");
//        kaodianTest.setName("南京睿煌（南京市博览中心）");
//        kaodianList.add(kaodianTest);


        System.out.println("");
        System.out.println("-------------------------更新报名信息----------------------------");
        System.out.println("");

        String updateUrl = "http://user.chinapmp.c|n/App_Ajax/SHOW.Ajax.User.Examsignedit,SHOW.Ajax.ajax?id=10868920&domain=user";
        //此处填你的报名信息
        String updateDataStr = "{\n" +
                "    \"JSON_DATA\": [\n" +
                "        {\n" +
                "            \"Name\": \"Id\",\n" +
                "            \"Value\": \"\"\n" +//需填
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"Stime\",\n" +
                "            \"Value\": \"/Date(1618289629223+0800)/\"\n" +//需填
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"Ed\",\n" +
                "            \"Value\": 10000044\n" +
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"Etitle\",\n" +
                "            \"Value\": \" 2021年6月20日项目管理资格认证考试\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"Stype\",\n" +
                "            \"Value\": 101\n" +
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"StypeName\",\n" +
                "            \"Value\": \"项目管理师(PMP®)\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"Xing\",\n" +
                "            \"Value\": \"\"\n" +//需填
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"Zhong\",\n" +
                "            \"Value\": \"\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"Ming\",\n" +
                "            \"Value\": \"\"\n" +//需填
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"Peixunjigou\",\n" +
                "            \"Value\": \"515\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"Peixunjigouming\",\n" +
                "            \"Value\": \"北京光环致成国际管理咨询股份有限公司\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"PMIUname\",\n" +
                "            \"Value\": \"\"\n" +//需填
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"PMIUpass\",\n" +
                "            \"Value\": \"\"\n" +//需填
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"IsPMIUser\",\n" +
                "            \"Value\": false\n" +
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"PMINumber\",\n" +
                "            \"Value\": \"\"\n" +//需填
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"_PMIUtimeB\",\n" +
                "            \"Value\": \"\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"_PMIUtimeE\",\n" +
                "            \"Value\": \"\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"PMItimeB\",\n" +
                "            \"Value\": \"/Date(1618070400000+0800)/\"\n" +//需填
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"PMItimeE\",\n" +
                "            \"Value\": \"/Date(1649606400000+0800)/\"\n" +//需填
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"Kaodian\",\n" +
                "            \"Value\": \"209\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"Kaodianming\",\n" +
                "            \"Value\": \"深圳才聚-南山区（广东新安职业技术学院）\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"Sstate\",\n" +
                "            \"Value\": 0\n" +
                "        },\n" +
                "        {\n" +
                "            \"Name\": \"PMIID\",\n" +
                "            \"Value\": \"\"\n" +//需填
                "        }\n" +
                "    ]\n" +
                "}\n" +
                " ";
        try {
            JSONObject updateJson = JSONObject.parseObject(updateDataStr);
            JSONArray dataArr = updateJson.getJSONArray("JSON_DATA");
            int times = 0;
            while (true){
                times++;
                if(pmp2.success){
                    return;
                }
                if(kaodianList.size()==0){
                    for(int i=0;i<3;i++){
                        System.out.println("考点都没了，赶快加新地区的考点！！！");
                    }
                    return;
                }
                for (int i=0;i<dataArr.size();i++){
                    JSONObject item = dataArr.getJSONObject(i);
                    if("Kaodian".equalsIgnoreCase(item.getString("Name"))){
                        item.put("Value", kaodianList.get(0).getCode());
                    }else if("Kaodianming".equalsIgnoreCase(item.getString("Name"))){
                        item.put("Value", kaodianList.get(0).getName());
                    }
                }
                CloseableHttpClient httpClient = HttpClients.createDefault();
                try {
                    HttpPost httpPost = new HttpPost(updateUrl);
                    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
                    httpPost.setConfig(requestConfig);
                    httpPost.setHeader("Content-Type", "text/plain; charset=UTF-8");
                    httpPost.setHeader("Cookie", "SYSTEM_ONLY_COOKIE_NAME=E4D46EC44AF3B17B9EF2063D047F317D; SYSTEM_TEMP_COOKIE_NAME=4E435AFE3130C859186F052A9DD19134; user="+user+"; Hm_lvt_ce48bdfcf41472b5d96a1d490af19487="+time+"; Hm_lpvt_ce48bdfcf41472b5d96a1d490af19487="+time2);
                    httpPost.setHeader("Cache-Control", "no-cache");
                    httpPost.setHeader("Connection", "keep-alive");
                    httpPost.setHeader("X-UNEXT.Ajax-Method", "Save");
                    httpPost.setHeader("X-UNEXT.Ajax-Token", "cf9c94d1.1337E74021394F067ECF73E520CCA448");
                    HttpEntity httpEntity = new StringEntity(updateJson.toString(), "UTF-8");
                    httpPost.setEntity(httpEntity);
                    HttpResponse response = null;
                    try {
                        response = httpClient.execute(httpPost);
                    } catch (IOException e) {
                        System.out.println("["+times+"] >> 请求超时");
                        httpClient.close();
                        continue;
                    }
                    int statusCode = response.getStatusLine().getStatusCode();
                    System.out.println("["+times+"] >> "+Calendar.getInstance().getTime().toString()+" >> "+statusCode);
                    if(statusCode==200){
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            InputStream is = entity.getContent();
                            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                            String line = br.readLine();
                            StringBuilder sb = new StringBuilder();
                            while (line != null) {
                                sb.append(line + "\n");
                                line = br.readLine();
                            }
                            String updateMsg = sb.toString();
                            JSONObject updateMsgJson = JSONObject.parseObject(updateMsg);
                            if(updateMsgJson.getString("error")!=null
                                    && "考点报名人数已达上限，请选择其他考点，如有疑问，与考点联系！".equalsIgnoreCase(updateMsgJson.getString("error"))){
                                System.out.println("此考点已满："+kaodianList.get(0).getCode()+":::"+kaodianList.get(0).getName());
                                kaodianList.remove(0);
                            }else{
                                pmp2.success = true;
                                System.out.println("报名成功！！！"+kaodianList.get(0).getCode()+":::"+kaodianList.get(0).getName());
                                return;
                            }
                        }
                    }
                }finally {
                    httpClient.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("");
        System.out.println("done！运行结束。");
    }

    public static class Kaodian{
        private String code;
        private String name;

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

}